package dz.chuxin.framework.widget.recycler;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.FrameLayout;

import dz.chuxin.framework.R;

/**
 * RecyclerView封装
 * Created by chuxin on 2016/6/30.
 */
public class ChuXinRecyclerView extends FrameLayout implements SwipeRefreshLayout.OnRefreshListener {

    // RecyclerView有可能处于的三种状态（空闲/下拉刷新/加载更多）
    public static final int ACTION_IDLE = 0;
    public static final int ACTION_PULL_TO_REFRESH = 1;
    public static final int ACTION_LOAD_MORE = 2;

    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerView;
    private OnRecyclerRefreshListener listener;
    private ILayoutManager mLayoutManager;
    private BaseRecyclerAdapter mRecyclerAdapter;

    private int mCurrentState = ACTION_IDLE;
    private boolean isLoadMoreEnabled = false;
    private boolean isPullToRefreshEnabled = true;
    private int mLoadMoreThreshold = 4;

    public ChuXinRecyclerView(Context context) {
        this(context, null);
    }

    public ChuXinRecyclerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ChuXinRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setUpView();
    }

    // Inflater布局文件并查找配置RecyclerView
    private void setUpView() {
        LayoutInflater.from(getContext()).inflate(R.layout.widget_refresh_recycler_view, this, true);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        // RecyclerView添加滚动监听器，用来判断是否满足加载更多数据
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (mCurrentState == ACTION_IDLE && isLoadMoreEnabled && isNeedLoadMore()) {
                    mCurrentState = ACTION_LOAD_MORE;
                    // 通知Adapter显示"加载更多"布局
                    mRecyclerAdapter.onLoadMoreStateChanged(true);
                    // 加载更多进行时禁用SwipeRefreshLayout下拉刷新功能
                    mSwipeRefreshLayout.setEnabled(false);
                    // 通知监听器去加载更多数据，操作为ACTION_LOAD_MORE
                    listener.onRefresh(ACTION_LOAD_MORE);
                }
            }
        });
    }

    // 判断是否需要加载更多
    private boolean isNeedLoadMore() {
        int lastVisibleItemPosition = mLayoutManager.findLastVisiblePosition();
        int totalCount = mLayoutManager.getLayoutManager().getItemCount();
        return totalCount - lastVisibleItemPosition <= mLoadMoreThreshold;
    }

    // 设置加载更多阈值
    public void setLoadMoreThreshold(int loadMoreThreshold) {
        mLoadMoreThreshold = loadMoreThreshold;
    }

    /**
     * 启用/禁用加载更多
     */
    public void enableLoadMore(boolean enable) {
        isLoadMoreEnabled = enable;
    }

    /**
     * 启用/禁用下拉刷新
     */
    public void enablePullToRefresh(boolean enable) {
        isPullToRefreshEnabled = enable;
        mSwipeRefreshLayout.setEnabled(enable);
    }

    // 设置RecyclerView布局管理器
    public void setLayoutManager(ILayoutManager manager) {
        this.mLayoutManager = manager;
        mRecyclerView.setLayoutManager(manager.getLayoutManager());
    }

    // addItemDecoration
    public void addItemDecoration(RecyclerView.ItemDecoration decoration) {
        if (decoration != null) {
            mRecyclerView.addItemDecoration(decoration);
        }
    }

    // 设置 RecyclerView 列表适配器
    public void setAdapter(BaseRecyclerAdapter adapter) {
        this.mRecyclerAdapter = adapter;
        mRecyclerView.setAdapter(adapter);
        mLayoutManager.setUpAdapter(adapter);
    }

    // 开启刷新
    public void setRefreshingOn() {
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
                onRefresh();
            }
        });
    }

    // 刷新（下拉刷新或加载更多）完成
    public void onRefreshComplete() {
        switch (mCurrentState) {
            case ACTION_PULL_TO_REFRESH:
                // 如果是下拉刷新完成，关闭SwipeRefreshLayout的刷新状态
                mSwipeRefreshLayout.setRefreshing(false);
                break;
            case ACTION_LOAD_MORE:
                // 如果是加载更多操作完成，通知Adapter隐藏"加载更多"布局
                mRecyclerAdapter.onLoadMoreStateChanged(false);
                // 同时如果下拉刷新没有禁用的话启用SwipeRefreshLayout的刷新功能
                if (isPullToRefreshEnabled)
                    mSwipeRefreshLayout.setEnabled(true);
                break;
        }
        mCurrentState = ACTION_IDLE;
    }

    // 下拉刷新
    @Override
    public void onRefresh() {
        mCurrentState = ACTION_PULL_TO_REFRESH;
        listener.onRefresh(ACTION_PULL_TO_REFRESH);
    }

    public void setOnRecyclerRefreshListener(OnRecyclerRefreshListener listener) {
        this.listener = listener;
    }

    // RecyclerView刷新（包括下拉刷新和加载更多）监听器
    public interface OnRecyclerRefreshListener {
        void onRefresh(int action);
    }
}
